package com.jcfy.project.module.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.jcfy.common.utils.DateUtils;
import com.jcfy.project.module.domain.*;
import com.jcfy.project.module.domain.vo.CartsVo;
import com.jcfy.project.module.mapper.TOrderGoodsMapper;
import jodd.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jcfy.project.module.mapper.TOrderMapper;
import com.jcfy.project.module.service.ITOrderService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 订单Service业务层处理
 *
 * @author jiangfeng
 * @date 2020-08-05
 */
@Service
public class TOrderServiceImpl implements ITOrderService {
    @Autowired
    private TOrderMapper tOrderMapper;
    @Autowired
    private TOrderGoodsMapper tOrderGoodsMapper;

    // 记录最后一次生成订单流水号的编号
    private static int trace_num = 1;
    // 记录最后一次生成订单流水号的日期(格式：yyyyMMdd)
    private static String trace_date;

    /**
     * 查询订单
     *
     * @param orderId 订单ID
     * @return 订单
     */
    @Override
    public TOrder selectTOrderById(Long orderId) {
        return tOrderMapper.selectTOrderById(orderId);
    }

    /**
     * 查询订单列表
     *
     * @param tOrder 订单
     * @return 订单
     */
    @Override
    public List<TOrder> selectTOrderList(TOrder tOrder) {
        return tOrderMapper.selectTOrderList(tOrder);
    }

    /**
     * 新增订单
     *
     * @param tOrder 订单
     * @return 结果
     */
    @Override
    public int insertTOrder(TOrder tOrder) {
        tOrder.setCreateTime(DateUtils.getNowDate());
        return tOrderMapper.insertTOrder(tOrder);
    }

    /**
     * 修改订单
     *
     * @param tOrder 订单
     * @return 结果
     */
    @Override
    public int updateTOrder(TOrder tOrder) {
        tOrder.setUpdateTime(DateUtils.getNowDate());
        return tOrderMapper.updateTOrder(tOrder);
    }

    /**
     * 批量删除订单
     *
     * @param orderIds 需要删除的订单ID
     * @return 结果
     */
    @Override
    public int deleteTOrderByIds(Long[] orderIds) {
        return tOrderMapper.deleteTOrderByIds(orderIds);
    }

    /**
     * 删除订单信息
     *
     * @param orderId 订单ID
     * @return 结果
     */
    @Override
    public int deleteTOrderById(Long orderId) {
        return tOrderMapper.deleteTOrderById(orderId);
    }

    @Override
    @Transactional
    public TOrder createOrder(String carts, String team, Long userId, String amount, String consigneeName, String consigneeMobile, String consigneeProvince, String consigneeCity, String consigneeArea, String consigneeAddress, String remark) {
        try {
            // 删除无效订单失败
            TOrder order = new TOrder();
            order.setUserId(userId);
            order.setBusinessStatus(1);
//            List<TOrder> orderList = tOrderMapper.selectTOrderList(order);
//            if (!orderList.isEmpty()) {
//                Long[] orderIds = new Long[orderList.size()];
//                for (int i = 0; i < orderList.size(); i++) {
//                    orderIds[i] = orderList.get(i).getOrderId();
//                }
//                int result1 = tOrderMapper.deleteTOrdersByIds(orderIds);
//                int result2 = tOrdersDetailMapper.deleteTOrdersDetailByOrderIds(orderIds);
//                if (result1 <= 0 || result2 <= 0) {
//                    throw new RuntimeException("[订单创建][状态#失败][原因# 删除无效订单失败]");
//                }
//            }

            // 创建订单
            order.setUserId(userId);
            order.setTraceNo(createOrderTraceNo());
            order.setBusinessType(1);
            order.setGoodsPrice(new BigDecimal(amount));
            order.setOrderPrice(new BigDecimal(amount));
            order.setAmount(new BigDecimal(amount));
//            order.setConsigneeName(consigneeName);
//            order.setConsigneeMobile(consigneeMobile);
//            order.setConsigneeProvince(consigneeProvince);
//            order.setConsigneeCity(consigneeCity);
//            order.setConsigneeArea(consigneeArea);
//            order.setConsigneeAddress(consigneeAddress);
            order.setFreightType(0);
            order.setRemark(remark);
            TTeam tTeam = JSONArray.parseObject(team, TTeam.class);
            order.setSaleInfo(tTeam.getName()+','+tTeam.getMobile());
            order.setTakeInfo(tTeam.getName()+','+tTeam.getMobile());
            order.setTakeAddress(tTeam.getAddress());
            int add = tOrderMapper.insertTOrder(order);
            if (add == 0) {
                throw new RuntimeException("订单创建失败");
            }
            // 创建订单商品明细
            createOrderGoods(order.getOrderId(), carts);
            return order;
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    @Override
    public TOrder getOrderByTraceNo(String traceNo) {
        return tOrderMapper.getOrderByTraceNo(traceNo);
    }

    @Override
    public TOrder paySuccess(String traceNo, Integer payType, String payAccount, String payNo) {
        if (StringUtil.isBlank(traceNo) || payType == null || StringUtil.isBlank(payAccount) || StringUtil.isBlank(payNo)) {
            return null;
        }
        TOrder order = tOrderMapper.getOrderByTraceNo(traceNo);
        if (order == null) {
            throw new RuntimeException("[订单更新][状态#失败][原因# 订单不存在]");
        }
        /**
         * 添加商户收支明细
         */
        TAccountDetail accountDetail = new TAccountDetail();
        accountDetail.setAmount(order.getAmount());
        accountDetail.setOrderId(order.getOrderId());
        accountDetail.setStatus(1);
        accountDetail.setType(1);
//        accountDetail.setUserId(group.getUserId());
//        int insertTAccountDetail = accountDetailMapper.insertTAccountDetail(accountDetail);
//        if (insertTAccountDetail <= 0) {
//            throw new RuntimeException("[订单更新][状态#失败][原因# 添加商户收支明细失败]");
//        }
//        TAccount account = accountMapper.selectTAccountList(new TAccount(group.getUserId())).get(0);
//        account.setToBePresent(account.getToBePresent().add(order.getAmount()));
//        int updateTAccount = accountMapper.updateTAccount(account);
//        if (updateTAccount <= 0) {
//            throw new RuntimeException("[订单更新][状态#失败][原因# 添加商户待结算失败]");
//        }

        // 支付方式
        order.setPayType(payType);
        // 支付账户
        order.setPayAccount(payAccount);
        // 支付单号
        order.setPayNo(payNo);
        // 支付时间
        order.setPayTime(new Date());
        order.setBusinessStatus(2);// 待发货
        int result = tOrderMapper.updateTOrder(order);
        if (result <= 0) {
            throw new RuntimeException("[订单更新][状态#失败]");
        }
        return order;
    }

    /**
     * 生成订单流水号(格式：yyyyMMddHHmmss000001)
     *
     * @return 生成的订单流水号
     */
    public synchronized String createOrderTraceNo() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat formatHms = new SimpleDateFormat("HHmmss");
        Date now = new Date();
        String nowDate = format.format(now);
        String traceNo = null;
        if (StringUtils.isBlank(trace_date)) {
            // 初始化
            trace_date = nowDate;
            // 获取当天最后一个订单流水号
            String lastTraceNo = tOrderMapper.getLastTraceNo(nowDate);
            if (StringUtils.isNotBlank(lastTraceNo)) {
                // 延续已有的订单编号
                trace_num = Integer.parseInt(lastTraceNo.substring(14)) + 1;
            }
        } else if (nowDate.equals(trace_date)) {
            // 同一天的订单，编号+1
            trace_num = trace_num + 1;
        } else {
            // 不是同一天的订单，则初始化编号
            trace_date = nowDate;
            trace_num = 1;
        }
        traceNo = trace_date + formatHms.format(now) + String.format("%06d", trace_num);
        return traceNo;
    }

    /**
     * 创建订单商品明细
     * @param orderId
     * @param carts
     */
    private void createOrderGoods(Long orderId, String carts) {
        List<CartsVo> CartsVoList = JSONArray.parseArray(carts, CartsVo.class);
        CartsVoList.forEach((car) -> {
            TGoods tGoods = JSONArray.parseObject(car.getGoods(), TGoods.class);
            TOrderGoods orderGoods = new TOrderGoods();
            orderGoods.setOrderId(orderId);
            orderGoods.setSupplierId(tGoods.getSupplierId());
            orderGoods.setGoodsId(tGoods.getGoodsId());
            orderGoods.setGoodsName(tGoods.getName());
            orderGoods.setNumber(car.getCount());
            orderGoods.setPrice(tGoods.getFavorablePrice());
            orderGoods.setSpecifications(tGoods.getSpecifications());
            orderGoods.setPicUrl(tGoods.getPicUrl());
            int i = tOrderGoodsMapper.insertTOrderGoods(orderGoods);
            if (i <= 0) {
                throw new RuntimeException("创建订单商品明细");
            }
        });
    }

}
